<!-- 正文开始 -->
<div class="layui-fluid" id="workPlanSearch">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form toolbar" lay-filter="workPlanSearch">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-label">科室</label>
                        <div class="layui-inline item">
                            <select name="deptCode" lay-filter="workPlan-deptCode" >
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-label">计划日期</label>
                        <div class="layui-inline" style="width:90px;">
                            <input name="planDateFrom" class="layui-input" type="text" placeholder="yyyy-MM-dd"/>
                        </div>
                        <label class="layui-label">-</label>
                        <div class="layui-inline" style="width:90px;">
                            <input name="planDateTo" class="layui-input" type="text" placeholder="yyyy-MM-dd"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-label">计划项</label>
                        <div class="layui-inline item">
                            <select name="workType" lay-filter="workPlan-workType">
                                <option value="" data-default="">所有</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn icon-btn btnSearch"><i class="layui-icon">&#xe615;</i>搜索</button>
                        <button class="layui-btn icon-btn btnAdd"><i class="layui-icon">&#xe654;</i>添加</button>
                        <button class="layui-btn icon-btn btnSave layui-btn-normal"><i class="layui-icon layui-icon-ok"></i>保存</button>
                    </div>
                </div>
            </div>
            <div class="workPlanTableWrapper">
                <table class="layui-table" id="workPlanTable" lay-filter="workPlanTable"></table>
            </div>
        </div>
    </div>
</div>

<style>
    #workPlanSearch .workPlanTableWrapper td[data-field='workType'] .layui-table-cell {
        overflow: visible !important;
    }
</style>

<!-- 表格操作列 -->
<script type="text/html" id="tpl-workPlanTable-operator">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="tpl-workPlanTable-status">
    <input type="checkbox" lay-filter="tpl-workPlanTable-status" value="{{d.id}}" lay-skin="switch" lay-text="有效|取消"
           {{d.status==1 ? 'checked' : ''}}/>
</script>

<script>
    layui.use(['layer', 'table', 'form', 'http', 'tools','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var table = layui.table;
        var form = layui.form;
        var http = layui.http;
        var tools = layui.tools;
        var laydate = layui.laydate;
        
        var $view = $("#workPlanSearch");
        var $tbview = $view.find(".workPlanTableWrapper");
        var $deptCode = $view.find("select[name='deptCode']");
        var $planDateFrom = $view.find("input[name='planDateFrom']");
        var $planDateTo = $view.find("input[name='planDateTo']");
        var $workType = $view.find("select[name='workType']");
        var workPlanTableIns;
        var tmpParam = {bedList:[]};
        var orderByClause = "planDate,workType";

        tools.select.deptCodeOptions($deptCode);
        $planDateFrom.val(tools.todayStr());
        $planDateTo.val(tools.todayStr());
        laydate.render({elem:$planDateFrom.selector,value:tools.todayStr()});
        laydate.render({elem:$planDateTo.selector,value:tools.todayStr()});

        var fnGetBedList = function(d){
            if(!d){
                return "";
            }
            var list = [];

            if(d && d.bedList && d.bedList.length>0){
                layui.each(d.bedList,function (index,item) {
                    list.push(item.bedName2);
                });
                return list.join("&nbsp;&nbsp;");
            }else{
                return "";
            }
        };
        var fnGetSearchParam = function () {
            return {
                orderByClause: orderByClause,
                deptCode: $deptCode.val(),
                planDateFrom: $planDateFrom.val(),
                planDateTo: $planDateTo.val(),
                workType: $workType.val()
            };
        };
        var fnGetWorkTypeSelect = function(d){
            if(!d){
                return "";
            }
            return '<select data-id="' + (d.id || '') + '" lay-filter="tpl-workPlanTable-workType">'
                +tools.select.listToOptions({list:tmpParam.workTypeList,currValue:d.workType})
                +'</select>';
        };

        var fnRenderPlanDateTime = function(){
            $tbview.find(".planDate").each(function (i) {
                var that = this;
                layui.laydate.render({
                    elem: that,
                    format: "yyyy-MM-dd",
                    done: function (value, date) {
                        var idx = $(that).parents("tr:eq(0)").attr("data-index");
                        var data = {id: $(that).attr("data-id"), planDate: value};
                        workPlanTableIns.updateCache()
                        workPlanTableIns.saveDelta(idx,data);
                    }
                });
            });
            $tbview.find(".planTime").each(function (i) {
                var that = this;
                layui.laydate.render({
                    elem: that,
                    type: 'time',
                    format: "HH:mm:ss",
                    done: function (value, date) {
                        var idx = $(that).parents("tr:eq(0)").attr("data-index");
                        var data = {id: $(that).attr("data-id"), planTime: value};
                        workPlanTableIns.saveDelta(idx,data);
                    }
                });
            });
        };

        var fnRender = function (workTypeList) {
            tmpParam.workTypeList = workTypeList;
            tools.select.options($workType,workTypeList);

            form.render('select','workPlanSearch');
            //渲染表格
            workPlanTableIns = table.render({
                id: 'workPlanTable',
                elem: '#workPlanTable',
                method: 'post',
                contentType: "application/json",
                url: http.base_server + 'workPlan/list',
                where: fnGetSearchParam(),
                page: true,
                cellMinWidth: 100,
                height: 'full-200',
                limits : [10,20,30,40,50,100],
                limit : 20,
                autoSort: false,
                request: {
                    pageName: 'pageNum',
                    limitName: 'pageSize'
                },
                cols: [[
                    {type: 'numbers'},
                    {field: 'workType', sort:true, title: '计划项',width:120, templet:fnGetWorkTypeSelect},
                    {field: 'frequency', title: '频率',width:120, edit: 'text'},
                    {field: 'planDate', sort:true, title: '日期',width:90, templet: function (d) {
                            return '<input type="text" name="planDate" lay-verify="date" value="' + (d.planDate || '') + '" data-id="' + (d.id || '')+ '" placeholder="" readonly="readonly" class="layui-input layui-input-date planDate" />';
                        }
                    },
                    {field: 'planTime', title: '时间',width:90, templet: function (d) {
                            return '<input type="text" name="planTime" lay-verify="date" value="' + (d.planTime || '') + '" data-id="' + (d.id || '') + '" placeholder="" readonly="readonly" class="layui-input layui-input-date planTime" />';
                        }
                    },
                    {field: 'bedList', title: '床号',width:400, event:'bed', templet:fnGetBedList},
                    {field: 'remark', title: '备注',width:200, edit: 'text'},
                    {field: 'status', templet: '#tpl-workPlanTable-status', title: '状态',width:70, align:"center"},
                    {align: 'center', toolbar: '#tpl-workPlanTable-operator', title: '操作', width: 80},
                    {field: 'updateTime', title: '更新时间'},
                    {field: 'updateByWho', title: '更新人'}
                ]],
                error: function(code,msg){
                    http.fail(code,msg);
                },
                done: function (res, curr, count){
                    fnRenderPlanDateTime();
                }
            });
        };

        var fnSearch = function(){
            var param = fnGetSearchParam();
            workPlanTableIns.reload({where: param,page: {curr: 1}});
        };
        form.on('select(workPlan-deptCode)',function(data){
            http.get('bed/getRefList', {deptCode: $deptCode.val()}, function (res) {
                tmpParam.bedList = res.data;
                if(res.ok) {
                    fnSearch();
                }
            });
        });
        form.on('select(workPlan-workType)',function(data){
            fnSearch();
        });

        // 搜索按钮点击事件
        $view.find(".btnSearch").click(function () {
            fnSearch();
        });
        table.on("sort(workPlanTable)",function(obj){
            orderByClause = (obj.field || '')+ ' ' + (obj.type || '');
            fnSearch();
        });

        // 添加按钮点击事件
        $view.find(".btnAdd").click(function () {
            workPlanTableIns.addRow({
                frequency:'',
                deptCode:$deptCode.val(),
                workType:$workType.find("option:eq(1)").attr("value") || '',
                planDate:tools.todayStr(),
                status:1,
                bedList:[]
            });
            fnRenderPlanDateTime();
        });

        // 修改状态
        form.on('switch(tpl-workPlanTable-status)', function (obj) {
            var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
            var data = {id: obj.elem.value, status: obj.elem.checked ? 1 : 0};
            workPlanTableIns.saveDelta(idx,data);
        });

        table.on('edit(workPlanTable)',function (row) {
            var idx = row.tr.attr("data-index");
            var data = {};
            data.id = row.data.id;
            data[row.field] = row.value;
            workPlanTableIns.saveDelta(idx,data);
        });
        form.on('select(tpl-workPlanTable-workType)', function (obj) {
            var field = obj.othis.parents("td:eq(0)").attr("data-field");
            var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
            var data = {id: obj.elem.getAttribute("data-id")};
            data[field] = obj.value;
            workPlanTableIns.saveDelta(idx, data);
        });

        $view.find(".btnSave").click(function () {
            var data = workPlanTableIns.getDelta();
            if(!data){return;}
            http.post('workPlan/saveBatch',JSON.stringify(data),function(res){
                if(res.ok){
                    workPlanTableIns.updateCache(res.data);
                    workPlanTableIns.resetDelta();
                    http.okMsg(res.msg);
                }
            });
        });

        var fnShowBedList = function(rowObj){
            tools.open({
                type:1,
                area : ["400px", "560px"],
                title: '请选择',
                content : '<div><table id="workPlanBedTable"></table></div>',
                btn: ['确定','取消'],
                yes: function(index, layero){
                    var list = table.checkStatus('workPlanBedTable').data;
                    var beds = [];
                    layui.each(list,function(idx,item){
                       beds.push({bedId:item.id, bedCode:item.bedCode, bedName: item.bedName, bedName2:item.bedName2});
                    });
                    var idx = rowObj.tr.attr("data-index");
                    workPlanTableIns.updateRow(idx,{id:(rowObj.data.id||''), bedList:beds});
                    var bedCodes = fnGetBedList({bedList:beds});
                    rowObj.tr.find("td[data-field='bedList'] div").html(bedCodes);
                    layer.closeAll();
                },
                success : function(index, layero) {
                    table.render({
                        id: 'workPlanBedTable',
                        elem: '#workPlanBedTable',
                        height: 450,
                        page: false,
                        cols: [[
                            {type:'checkbox'},
                            {field: 'bedCode', title: '床号', width:80, sort: true},
                            {field: 'bedName', title: '床名', width:100, sort: true},
                            {field: 'patientName', title: '病人', width:100, sort: true}
                            ]],
                        data: tmpParam.bedList
                    })
                }
            })
        };

        table.on('tool(workPlanTable)', function(rowObj) {
            var data = rowObj.data;
            if (data && rowObj.event === 'bed') {
                //标明弹框那些行已经选定
                layui.each(tmpParam.bedList,function(i,item1){
                    item1.LAY_CHECKED = false; //默认没有选定
                    if(data.bedList) {
                        for (var j = 0; j < data.bedList.length; j++) {
                            var item2 = data.bedList[j];
                            if (item1 && item2 && item1.bedCode == item2.bedCode) {
                                item1.LAY_CHECKED = true;   //已经选定的
                                break;
                            }
                        }
                    }
                });
                fnShowBedList(rowObj);
            }else if (rowObj.event === 'edit') { //修改
            } else if (rowObj.event === 'del') { //删除
                layer.confirm("确定删除该行?",{btn:["确定","取消"]},
                    function(index,obj) {
                        layer.closeAll('dialog');
                        rowObj.del();
                    }
                );
            }
        });

        http.get('codelist/listItemByName',{listName:'WorkType'},function(res){
            if(res.ok) {
                var workTypeList = res.data;
                http.get('bed/getRefList', {deptCode: $deptCode.val()}, function (res) {
                    tmpParam.bedList = res.data;
                    if(res.ok) {
                        fnRender(workTypeList);
                    }
                });
            }
        });

    });

</script>